import 'package:flutter/material.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';


/*
 全局路由监听器
 实现page的重新入栈监听...
 */
class XSDKNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    //XLogUtils.printLog('---XSDKNavigatorObserver,didPush进入当前新页面: ${route.settings.name},Previous上一界面=${previousRoute?.settings.name}');
    //通知进入后台的page
    XSDKNavigatorObserverNotify.notifyPageStatus(type:1, pageName: '${previousRoute?.settings.name}',);

  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    //XLogUtils.printLog('---XSDKNavigatorObserver,didPop退出页面: ${route.settings.name},Previous返回当前页面=${previousRoute?.settings.name}');
    //通知重新进入前的page
    XSDKNavigatorObserverNotify.notifyPageStatus(type:2, pageName: '${previousRoute?.settings.name}',);

  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    super.didRemove(route, previousRoute);
    XLogUtils.printLog('---XSDKNavigatorObserver,didRemove: ${route.settings.name},Previous=${previousRoute?.settings.name}');
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute:newRoute, oldRoute:oldRoute);
    XLogUtils.printLog('---XSDKNavigatorObserver,didReplace: ${newRoute?.settings.name},Previous=${oldRoute?.settings.name}');
  }

  @override
  void didStartUserGesture(Route route, Route? previousRoute) {
    super.didStartUserGesture(route, previousRoute);
    XLogUtils.printLog('---XSDKNavigatorObserver,didStartUserGesture: ${route.settings.name},Previous=${previousRoute?.settings.name}');
  }

  @override
  void didStopUserGesture() {
    super.didStopUserGesture();
    XLogUtils.printLog('---XSDKNavigatorObserver,didStopUserGesture');
  }


}


typedef XFunctionRouteListener<T> = void Function(
    int type,//1切换进入后台,2重新进入前台
    String pageName
    );


/*
通知page切换到后台和重新进入前台
用于监听当前page
 */
abstract class XSDKNavigatorObserverNotify{

  static final List<XFunctionRouteListener> _listRouteListeners=[];

  //
  static void addRouteListener(XFunctionRouteListener listener){
    _listRouteListeners.add(listener);
  }
  //
  static void removeRouteListener(XFunctionRouteListener listener){
    _listRouteListeners.remove(listener);
  }

  //通知page重新进入前台还是切换进入后台
  static void notifyPageStatus({
    required int type, //1切换新页面,当前页面进入后台, 2重新进入前台
    required String pageName,
  }){

    try{
      for(XFunctionRouteListener listener in _listRouteListeners){
        listener(type,pageName);
      }
    }catch(e){
      //
    }
  }


}